/**
 * 	下拉table 服务端分页
 *  -- created by 胡扬东 2018.10.30
 * 
 *  支持多选
 *  -- lasted update by 胡扬东 2018.12.10
 */
Vue.component('h-select-table', {
  props: {
      label: {
        type: String,
        default: function() {
          return ''
        }
      },
      value: {
        default: function() {
          return ''
        }
      },
      labelField: {
        type: String,
        required: true,
        default: function() {
            return ''
        }
      },
      valueField: {
        type: String,
        required: true,
        default: function() {
          return ''
        }
      },
      readonly: {
        type: Boolean,
        default: function() {
            return false
        }
      },
      url: {
        type: String,
        required: true,
        default: function() {
          return ''
        }
      },
      searchOptions: {
        type: Array,
        default: function() {
          return []
        }
      },
      columns: {
        type: Array,
        required: true,
        default: function() {
          return []
        }
      },
      loading: {
        type: Boolean,
        default: function() {
          return false
        }
      },
      selection: {
        type: String,
        default: function() {
          return "single"
        }
      },
      selected: {
        type: Array,
        default: function() {
          return []
        }
      },
      unableChecked: {
        default: false
      }
  },
  template:
    '<div class="row no-wrap">'+
      '<q-input '+
        ':readonly="readonly" '+
        'style="display:none" '+
        ':after="[{ icon: \'arrow_drop_down\'}]" '+
        'v-model="cValue"> '+
      '</q-input> '+
      '<q-input '+
        ':readonly="readonly" '+
        'class="col-12" '+
        ':after="[{ icon: \'arrow_drop_down\'}]" '+
        'v-model="cLabel"> '+
        '<q-popover v-model="isShow" class="q-px-md" style="width:400px;min-height:400px" @show="request({pagination: serverPagination})" @hide="selectedConfirm"> '+
          '<q-table '+
            'dense '+
            'hide-bottom '+
            'separator="cell" '+
            'color="secondary" '+
            ':data="tableData" '+
            'row-key="id"'+
            ':columns="cColumns" '+
            ':selection="selection" '+
            ':loading="cLoading" '+
            ':selected.sync="cSelected" '+
            ':pagination.sync="serverPagination" '+
            '@request="request" '+
            ':rows-per-page-options="[8]" '+
            'class="no-shadow"> '+
            '<template slot="top-right" slot-scope="props"> '+
              '<q-input  '+
                'class="search-group-left" '+
                'hide-underline '+
                'placeholder="输入查询" '+
                'v-model.trim="searchForm.value"></q-input> '+
              '<select  '+
                'class="search-group-right" '+
                'v-model="searchForm.key">'+
                  '<option v-for="o in searchOptions" :value="o.value">{{ o.label }}</option>'+
              '</select> '+
              '<q-btn '+
                'size="sm" '+
                'color="primary" '+
                '@click="request({pagination: serverPagination})" '+
                'class="q-ml-sm q-pa-sm"> '+
                '<span slot="loading"> '+
                  '<q-spinner-hourglass></q-spinner-hourglass> '+
                  '搜索中 '+
                '</span> '+
                '<q-icon name="search"></q-icon> '+
                '<span>查询</span> '+
              '</q-btn> '+
            '</template> '+
            '<template slot="body" slot-scope="props"> '+
              '<q-tr :props="props"> '+
                '<q-td > '+
                  '<q-checkbox :disable="unableChecked" color="primary" v-model="props.selected"></q-checkbox> '+
                '</q-td> '+
                '<q-td v-for="col in cColumns" :key="col.name" :props="props" > '+
                  '{{ props.row[col.name] }} '+
                '</q-td> '+
              '</q-tr> '+
            '</template> '+
          '</q-table> '+
          '<div class="row flex-center q-py-sm text-dark" style="font-size: 13px"> '+
            '<q-pagination '+
              'v-model="serverPagination.page" '+
              'input '+
              'boundary-links '+
              'direction-links '+
              'color="primary" '+
              ':max-pages="5" '+
              ':ellipses="true" '+
              ':max="pages"></q-pagination> '+
            '页 &nbsp; 共 {{ total }} 条 '+
          '</div> '+
        '</q-popover> '+
      '</q-input> '+
    '</div>',
  data: function() {
      return {
          cLabel: this.label? this.label: '',
          cValue: this.value? this.value: '',
          cReadonly: this.readonly,
          // 表格 组件配置
          cLoading: this.loading,
          cSelected: this.selected,
          selectSession: [],
          cUrl: this.url,
          // 内置参数
          searchForm: {
            key: this.searchOptions[0].value,
            value: this.label
          },
          serverPagination: {
              page: 1,
              rowsPerPage: 8,
              rowsNumber: 8
          },
          tableData: [],
          total: 0,
          isShow: false,
          visible: false
      }
  },
  computed: {
      cColumns: function() {
          return this.columns
      },
      pages: function() {
          return Math.ceil(this.total / this.serverPagination.rowsPerPage)
      }
  },
  mounted: function() {
      // this.request({
      //     pagination: this.serverPagination
      // })
  },
  watch: {
      'serverPagination.page': function (page) {
          this.request({
              pagination: this.serverPagination
          })
      },
      cSelected: function(cSelected) {
        // this.selectedConfirm()
        if (cSelected.length == 0) {
          this.cValue = ''
        }
      },
      value: function(value) {
        this.cValue = value
        console.log(this.cValue, 'value 属性值变化')
      },
      label: function(label) {
        this.cLabel = label
      }
  },
  methods: {
      request: function(arg) {
          this.serverPagination = arg.pagination
          var that = this
          this.cLoading = true
          var _data = {
            page: this.serverPagination.page,
            rows: this.serverPagination.rowsPerPage,
            sort: this.serverPagination.sortBy,
            order: this.serverPagination.descending == true? 'desc' : (this.serverPagination.descending == false? 'asc' : null)
          }
          _data[this.searchForm.key] = this.searchForm.value
          axios({
              method: 'post',
              url: this.cUrl,
              data: _data
          })
          .then(function(data) {
            that.tableData = data.rows
            // TODO:  拆分出来单独为一个fn  拓展使用  且有优化作用
            if (that.value != '') {
              var v = that.value+''
              v.split(',').forEach(function(e) {
                that.tableData.forEach(function(q) {
                  if (e == q[that.valueField]) {
                    // 去重
                    var flag = true
                    that.cSelected.forEach(function(s) {
                      if (s[that.valueField] == e) {
                        flag = false
                      }
                    })
                    if (flag) {
                      that.cSelected.push(q)
                    }
                  }
                })
              })
            } else {
              that.cSelected = []
            }
            that.cLoading = false
            that.total = data.total
          })
          .catch(function(err) {
              console.log(err)
          })
      },
      search: function() {
        this.request({
          pagination: this.serverPagination
        })
      },

      selectedConfirm: function() {
        var a = [], v = [], that = this, o = []
        this.cSelected.forEach(function(e) {
          a.push(e[that.labelField])	
          v.push(e[that.valueField])
          o.push(e)	// 整个对象塞入
        })
        this.cLabel = a.join(',')
        this.cValue = v.join(',')
        // 勾选表格时  暴露select事件
        console.log(o, '当前已选择')
        //  解决没有勾选时报错，o.length? o: [{}]
        this.$emit('select', o.length? o: [{}])
        this.cSelected = []
        // this.$emit('select', { label: this.cLabel, value: this.cValue})
      }
  }
})